<template>
  <div class="address-container">
    <van-address-list
      v-if="list.length"
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @click-item="clickItem"
    />
    <van-empty description="暂无地址数据" v-else>
      <van-button round type="danger" class="bottom-button" @click="onAdd">新增地址</van-button>
    </van-empty>
  </div>
</template>

<script>
export default {
  data() {
    return {
      chosenAddressId: null,
      list: []
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    clickItem (item, index) {
      this.$dialog.confirm({
        title: '温馨提示',
        message: '是否将该地址设为默认收货地址'
      }).then(async () => {
        const res = await this.$fetchPost('/home/member/setaddress', { id:  item.id})
        if (!res.success) {
          this.$toast(res.msg)
          return
        }
        if (this.$route.query.type === 'select') {
          window.history.back()
        } else {
          this.getList()
        }
      }).catch(() => {
        
      })
    },
    async getList() {
      const result = await this.$fetchGet("/home/member/address");
      if (!result.success) {
        this.$toast(result.msg);
        return;
      }
      this.list = result.data.list.map(item => {
        if (item.isdefault) {
          this.chosenAddressId = item.id
        }
        return {
          id: item.id,
          name: item.username,
          address: item.address,
          tel: item.telephone,
          zipcode: item.zipcode
        };
      });
    },
    onAdd() {
      this.$router.push({
        path: "/add-address",
        query: {
          type: "add"
        }
      });
    },
    onEdit(item, index) {
      this.$router.push({
        path: "/add-address",
        query: {
          type: "edit",
          address: item.address,
          id: item.id,
          name: item.name,
          tel: item.tel,
          zipcode: item.zipcode
        }
      });
    }
  }
};
</script>

<style lang="scss">
.address {
  &-item {
  }
}
</style>